import React, {Component} from 'react';

import './index.scss';
import { CRAWLER_TH } from 'config/table_config'

import CrawlerService from 'services/Crawler';

import ListTitleCon from 'components/commonCon/ListTitleCon';
import TableHeadCon from 'components/commonCon/TableHeadCon';
import TableBodyCon from './TableBodyCon';

import crawlerConfigData from 'config/crawler_config';

const crawlerService = new CrawlerService ();

class CrawlerCon extends Component {

  constructor(props) {
    super(props);

    this.state = {
      title: '数据爬虫管理',
      crawlerConfigData
    }
  }
  
  onCrawlClick (apiName, index) {
    const { crawlerConfigData } = this.state;

    crawlerConfigData[index].loading = true;

    this.setState({
      crawlerConfigData
    }, async ()=> {
      const result = await crawlerService.crawlAction(apiName),
            errorCode = result.error_code;

      crawlerConfigData[index].loading = false;
      
      this.setState({
        crawlerConfigData
      })

      if(errorCode === 0) {
        alert(`${crawlerConfigData[index].title}成功.`);
        return;
      }
      
      alert(`${crawlerConfigData[index].title}失败.`)
    })
  }

  render() {
    const { title } = this.state; //良好习惯，一定要解构
    return (
      <div className="list-container">
        {/* 公共组件 */}
        <ListTitleCon 
          title={title} 
          refreshHide = { true }/>
        <table className="list-table">
          <TableHeadCon thData={ CRAWLER_TH } />
          <TableBodyCon 
            crawlerConfigData = { crawlerConfigData }
            onCrawlClick = { this.onCrawlClick.bind(this)}
          />
        </table>
      </div>
    )
  }
}

export default CrawlerCon;